package com.yuanfeng.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.activity.dto.*;
import com.yuanfeng.activity.entity.*;
import com.yuanfeng.activity.feign.BaseServiceClient;
import com.yuanfeng.activity.feign.OrderServiceClient;
import com.yuanfeng.activity.mapper.*;
import com.yuanfeng.activity.service.ActivityPiecingTogetherService;
import com.yuanfeng.activity.utils.AccessTokenUtil;
import com.yuanfeng.activity.vo.*;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.dto.goods.ListPageQueryParamDTO;
import com.yuanfeng.commoms.dto.goods.NavSortLogoDTO;
import com.yuanfeng.commoms.dto.job.ExpireMarkIdUpdateDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.secverifyapiutil.Base64Utils;
import com.yuanfeng.commoms.vo.activity.AppPintuanGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.ExpireMarkIdUpdateParamVO;
import com.yuanfeng.commoms.vo.activity.JoinPintuanParamVO;
import com.yuanfeng.commoms.vo.activity.ModularGoodsVO;
import com.yuanfeng.commoms.vo.base.BaseSysConfigsVO;
import com.yuanfeng.commoms.vo.goods.GdsDetailsCommonQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @ClassName ActivityPiecingTogetherServiceImpl
 * @Description 拼团主表
 * @Author cyp
 * @Date 2023-05-25 14:27:05
 * @Version 1.0
 **/
@Service
public class ActivityPiecingTogetherServiceImpl extends ServiceImpl<ActivityPiecingTogetherMapper, ActivityPiecingTogetherEntity>
        implements ActivityPiecingTogetherService {
    @Autowired
    private ActivityPiecingTogetherMarkMapper activityPiecingTogetherMarkMapper;
    @Autowired
    private ActivityPiecingTogetherBuyerMapper activityPiecingTogetherBuyerMapper;
    @Autowired
    private ActivityPiecingTogetherTempMapper activityPiecingTogetherTempMapper;
    @Autowired
    private ActivityReductionPolicyGoodsMapper activityReductionPolicyGoodsMapper;
    @Autowired
    private ActivityReductionPolicyBaseMapper activityReductionPolicyBaseMapper;
    @Value("${domainName}")
    private String domainName;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private OrderServiceClient orderServiceClient;

    @Autowired
    private ActivityDiscountBaseMapper activityDiscountBaseMapper;

    @Autowired
    private ActivityDiscountGoodsMapper activityDiscountGoodsMapper;

    @Autowired
    private ActivitySeckillBaseMapper activitySeckillBaseMapper;

    @Autowired
    private ActivitySeckillGoodsMapper activitySeckillGoodsMapper;

    @Autowired
    private ActivityPiecingTogetherDetailMapper activityPiecingTogetherDetailMapper;

    private static final Logger LOG = LoggerFactory.getLogger(ActivityPiecingTogetherServiceImpl.class);
    @Override
    public AppPintuanGoodsQueryResultVO selectByGoodsId(Integer commonId, Integer goodsId) {
        return this.baseMapper.selectByGoodsId(commonId,goodsId);
    }

    @Override
    public ResponseResult querySurplusNum(String markId) {
        Integer surplusNum = this.baseMapper.selectSurplusNum(markId);
        if(surplusNum == null){
            return ResponseResult.fail(BizCodeEnume.MARKID_IS_NULL);
        }
        return ResponseResult.success(surplusNum);
    }

    @Override
    public ResponseResult addJoinPintuan(JoinPintuanParamVO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        // 查询该商品的拼团信息
        PintuanBaseMessageVO pintuanBaseMessage = this.baseMapper.selectPintuanId(param.getCommonId(),
                param.getGoodsId());
        if (null == pintuanBaseMessage) {
            return ResponseResult.fail(0, "发起拼团失败：无拼团信息");
        }
        Integer personNum = pintuanBaseMessage.getPersonNum();

        PintuanMarkMessageVO markMessage = new PintuanMarkMessageVO();
        markMessage.setCreatedTime(new Date());
        markMessage.setUserId(param.getUserId());
        markMessage.setUserAvatar(userInfo.getUserAvatar());
        markMessage.setUserName(userInfo.getUserName());
        markMessage.setDetailId(pintuanBaseMessage.getDetailId());
        markMessage.setType(param.getType());
        markMessage.setGoodsId(pintuanBaseMessage.getGoodsId());
        // 支付状态 0 未付款 1 已付款 2 以退款
        markMessage.setMarkId(param.getMarkId());
        markMessage.setPayTtart(0);

        Integer num = 1;
        Integer surplusNum = 1;
        // 0,等待成团。1为已成团，2为成团失败，3为已完成退款
        Integer status = 0;

        if (param.getIsMark().equals(1)) {

            if (num.equals(personNum)) {
                surplusNum = 0;
                // 成团
                status = 1;
            } else {
                surplusNum = personNum - num;
                status = 0;
            }

            // 发起新的拼团
            markMessage.setNum(num);
            markMessage.setSurplusNum(surplusNum);
            markMessage.setStatus(status);

            // 拼团，团长标识-我的拼团
            activityPiecingTogetherMarkMapper.insertPintuanMark(markMessage);

            // 购买人表
            markMessage.setRanking(1);
            activityPiecingTogetherBuyerMapper.insertPintuanBuyer(markMessage);

            // 获取订单号
            markMessage.setOrderId(param.getOrderId());
            activityPiecingTogetherTempMapper.insertPintuanTemp(markMessage);
        } else {

            /*-------------------------------拼团增加参与者-------------------------------------*/
            // 查询团长信息
            PintuanMarkMessageVO pintuanMarkMessage = this.baseMapper.selectMarkMessage(param.getMarkId());
            if (null != pintuanMarkMessage) {
                num = pintuanMarkMessage.getNum() + 1;
                surplusNum = pintuanMarkMessage.getSurplusNum() - 1;
                personNum = pintuanMarkMessage.getPersonNum();
                if (num.equals(personNum)) {
                    surplusNum = 0;
                    // 成团
                    status = 1;
                } else {
                    surplusNum = personNum - num;
                    status = 0;
                }
                // 更新团长信息
                markMessage.setNum(num);
                markMessage.setSurplusNum(surplusNum);
                markMessage.setStatus(status);
                markMessage.setMarkId(param.getMarkId());

                // 更新购买人信息
                markMessage.setRanking(num);
                activityPiecingTogetherBuyerMapper.insertPintuanBuyer(markMessage);

                // 更新团长信息
                activityPiecingTogetherMarkMapper.updateMarkMessage(markMessage);

                // 生成订单，获取订单号
                markMessage.setOrderId(param.getOrderId());

                activityPiecingTogetherTempMapper.insertPintuanTemp(markMessage);
            } else {
                return ResponseResult.fail(0, "发起拼团失败：无拼团信息");
            }
        }

        // 拼团成功 订单更新状态
        if (status.equals(1)) {
            ExpireMarkIdUpdateParamVO expireMark = new ExpireMarkIdUpdateParamVO();
            List<String> orderIdList = activityPiecingTogetherTempMapper.selectByMarkId(param.getMarkId());
            expireMark.setStatus(1);
            expireMark.setOrderIdList(orderIdList);
            RedisUtil.set(param.getMarkId(), JsonUtils.toString(expireMark), 20);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryAll(ListPageQueryParamDTO param) {
        try {
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            IPage<Map<String, Object>> page = this.baseMapper.queryBrandList(new Query<Map<String, Object>>().getPage(data),param);

            return ResponseResult.success(PageUtils.getPage(page));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult delete(Map<String, Object> param) {
        String orderId = (String) param.get("orderId");
        if (null != orderId) {
            ///查询该订单的markId userid
            ActivityPiecingTogetherTempEntity orderPintuanTempEntity = activityPiecingTogetherTempMapper.selectOne(new LambdaQueryWrapper<ActivityPiecingTogetherTempEntity>()
                    .eq(ActivityPiecingTogetherTempEntity::getOrderId, orderId));

            if (null != orderPintuanTempEntity && null != orderPintuanTempEntity.getMarkId() && null != orderPintuanTempEntity.getUserId()) {
                //拼团订单取消 删除当前用户在该拼团的信息 释放拼团名额
                activityPiecingTogetherTempMapper.delete(new LambdaQueryWrapper<ActivityPiecingTogetherTempEntity>()
                        .eq(ActivityPiecingTogetherTempEntity::getUserId, orderPintuanTempEntity.getUserId())
                        .eq(ActivityPiecingTogetherTempEntity::getMarkId, orderPintuanTempEntity.getMarkId()));

                activityPiecingTogetherBuyerMapper.delete(new LambdaQueryWrapper<ActivityPiecingTogetherBuyerEntity>()
                        .eq(ActivityPiecingTogetherBuyerEntity::getUserId, orderPintuanTempEntity.getUserId())
                        .eq(ActivityPiecingTogetherBuyerEntity::getMarkId, orderPintuanTempEntity.getMarkId()));

                //判断当前用户是否是团长 是 删除团 不是 人数减一
                Integer num = activityPiecingTogetherMarkMapper.selectCount(new LambdaQueryWrapper<ActivityPiecingTogetherMarkEntity>()
                        .eq(ActivityPiecingTogetherMarkEntity::getUserId, orderPintuanTempEntity.getUserId())
                        .eq(ActivityPiecingTogetherMarkEntity::getMarkId, orderPintuanTempEntity.getMarkId()));
                if (null != num && num > 0) {
                    //删除
                    activityPiecingTogetherMarkMapper.delete(new LambdaQueryWrapper<ActivityPiecingTogetherMarkEntity>()
                            .eq(ActivityPiecingTogetherMarkEntity::getUserId, orderPintuanTempEntity.getUserId())
                            .eq(ActivityPiecingTogetherMarkEntity::getMarkId, orderPintuanTempEntity.getMarkId()));
                } else {
                    ActivityPiecingTogetherMarkEntity markEntity = activityPiecingTogetherMarkMapper.selectOne(new LambdaQueryWrapper<ActivityPiecingTogetherMarkEntity>()
                            .eq(ActivityPiecingTogetherMarkEntity::getMarkId, orderPintuanTempEntity.getMarkId()));
                    //人数减一
                    activityPiecingTogetherMarkMapper.update(markEntity, new LambdaUpdateWrapper<ActivityPiecingTogetherMarkEntity>()
                            .eq(ActivityPiecingTogetherMarkEntity::getMarkId, orderPintuanTempEntity.getMarkId())
                            .set(ActivityPiecingTogetherMarkEntity::getSurplusNum, markEntity.getSurplusNum() - 1));
                }
                return ResponseResult.success();
            }
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult update(Map<Object, Object> map) {
        ActivityPiecingTogetherMarkEntity refundMarkMessage = activityPiecingTogetherMarkMapper.selectOne(new LambdaQueryWrapper<ActivityPiecingTogetherMarkEntity>()
                .eq(ActivityPiecingTogetherMarkEntity::getMarkId, map.get("markId").toString()));

        Integer status = 0;
        String userId=map.get("userId").toString();
        if (null != refundMarkMessage) {
            if (userId.equals(refundMarkMessage.getUserId())) {
                status = 2;
            }
            refundMarkMessage.setSurplusNum(refundMarkMessage.getSurplusNum() + 1);
            refundMarkMessage.setStatus(status);
            Integer num = refundMarkMessage.getNum() - 1;
            if (num.intValue() <= 0) {
                num = 0;
                status = 2;
            }
            refundMarkMessage.setNum(num);
            activityPiecingTogetherMarkMapper.updateById(refundMarkMessage);

        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryGoods(WebPinTuanParamDTO param) {
        try {
            Map<String, Object> map = new HashMap<>();
            //查询平台商品
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            IPage<GoodsPinTuanResultVO> page = this.baseMapper.queryPinTuanGoods(new Query<GoodsPinTuanResultVO>().getPage(data),param);

            List<GoodsPinTuanResultVO> results =  page.getRecords();
            if(null != results && 0 < results.size()){
                for (GoodsPinTuanResultVO result : results) {
                    //生成h5 二维码
                    byte[] b = QrCodeUtil.createQRCode(150, 150, domainName + "/h5/#/pages/description/descrption?goodsId=" + result.getGoodsId() + "&commonId=" + result.getCommonId());
                    // 转base 64
                    String orCode = QrCodeUtil.BASE_PREFIX + Base64Utils.encode(b);
                    result.setOrCode(orCode);
                    //生成app 二维码
                    System.out.println("/pages/description/descrption?goodsId=" + result.getGoodsId() + "&commonId=" + result.getCommonId()+"&type=\"pingTuan\"");
                    byte[] app = QrCodeUtil.createQRCode(150, 150, "/pages/description/descrption?goodsId=" + result.getGoodsId() + "&commonId=" + result.getCommonId()+"&type=\"pingTuan\"");
                    // 转base 64
                    String appOrCode = QrCodeUtil.BASE_PREFIX + Base64Utils.encode(app);
                    result.setAppOrCode(appOrCode);
                }
            }
            map.put("results",results);
            map.put("count",PageUtils.getPage(page).getTotalCount());
            //查询轮播图
            NavSortLogoDTO gdbNavSortLogoDTO = new NavSortLogoDTO();
            gdbNavSortLogoDTO.setConfigType("group_slide_picture_pc");
            ResponseResult resp1 = baseServiceClient.quertNavLogo(gdbNavSortLogoDTO);
            List<BaseSysConfigsVO> list = (List<BaseSysConfigsVO>) resp1.getData();
            map.put("images",list);
            return ResponseResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult selectMarkInfo(Map<String, Object> param) {
        ActivityPiecingTogetherMarkEntity entity=null;
        if(null!=param.get("id")){
            entity=activityPiecingTogetherMarkMapper.selectById(param.get("id").toString());
        }
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult updatePayStart(Map<String, Object> param) {
        String orderId = (String) param.get("orderId");
        if(null != orderId ){
            //查询该订单是否是拼团订单
            Integer count = activityPiecingTogetherTempMapper.queryPintByOrder(orderId);
            if(null != count && 0 < count){
                //修改拼团的支付状态
                Integer num = activityPiecingTogetherTempMapper.updatePintByOrder(orderId);
                if(num > 0){
                    return ResponseResult.success();
                }
                return ResponseResult.fail();
            }
        }
        return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
    }

    @Override
    public ResponseResult queryList(PintuanBaseListQueryDTO param) {
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<Map<String, Object>> page = activityPiecingTogetherTempMapper.selectModularizationPintuanBaseList(new Query<Map<String, Object>>().getPage(map),param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryGoodsPrice(Integer goodsId) {
        ModularGoodsVO modularGoodsVO = activityPiecingTogetherTempMapper.queryGoodsPrice(goodsId);
        return ResponseResult.success(modularGoodsVO);
    }

    @Override
    public ResponseResult queryGoodsAll(Map<String, Object> param) {

        IPage<GoodsPinTuanResultVO> page=this.baseMapper.queryGoodsAll(new Query<GoodsPinTuanResultVO>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult updateDisorder(Map<String, Object> param) {
        ActivityPiecingTogetherEntity entity = JSONObject.parseObject(JSON.toJSONString(param), ActivityPiecingTogetherEntity.class);
        this.baseMapper.update(entity,new LambdaQueryWrapper<ActivityPiecingTogetherEntity>()
                       .eq(ActivityPiecingTogetherEntity::getPintuanId,param.get("pintuanId").toString()));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryPintuanBaseList(Map<String, Object> param) {
        IPage<ReductionPolicyBaseListVO> page=this.baseMapper.queryPintuanBaseList(new Query<ReductionPolicyBaseListVO>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult modularizationQueryPintuanBasebyId(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        List<Integer> ids = new ArrayList<>();
        List resultList = new ArrayList();
        String type = null;
        try {
            type = (String) param.get("type");
            ids =(List<Integer>) param.get("id");
            if(null == type){
                return ResponseResult.fail(0, "type不能为null");
            }
            if(0 == ids.size()){
                return ResponseResult.fail(0, "拼团Id不能为null");
            }
            //查询拼团的商品详情
            if("pintuan".equals(type)){
                for (Integer id : ids) {
                    map2 = this.baseMapper.selectModularization(id);
                    map = this.baseMapper.selectModularizationPintuanBaseById(id);
                    map2.put("items",map);
                    resultList.add(map2);
                }
                return ResponseResult.success(resultList);
            }else if("zhekou".equals(type)){
                //查询限时折扣的商品详情
                for (Integer id : ids) {
                    map2 = activityDiscountBaseMapper.queryDiscountBase(id);
                    List<ActivityDiscountGoodsEntity> discountBaseDetail = activityDiscountGoodsMapper.selectDiscountBaseDetail(id);

                    map2.put("items",discountBaseDetail);
                    resultList.add(map2);
                }
                return ResponseResult.success(resultList);
            }else if("miaosha".equals(type)){
                //查询秒杀的商品详情
                for (Integer id : ids) {
                    map2 = activitySeckillBaseMapper.querySecondKill(id);
                    List<ActivitySeckillGoodsEntity> list = activitySeckillGoodsMapper.selectList(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                                            .eq(ActivitySeckillGoodsEntity::getSeckillId,id)
                                                            .groupBy(ActivitySeckillGoodsEntity::getCommonId));
                    map2.put("items",list);
                    resultList.add(map2);
                }
                return ResponseResult.success(resultList);
            }else{
                return ResponseResult.fail(BizCodeEnume.INVALID_PARAMETER);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public ResponseResult getPinTuanPoster(Map<String, Object> param) {
        Map<String,Object> respMap = new HashMap<>();
        String orCode = null;// 二维码的base64位
        try {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
            String markId = (String) param.get("markId");
            String type = (String) param.get("type");
            if(null == userInfo){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
            }
            if(null == markId || null == type){
                return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg());
            }
            //查询当前拼团
            GoodsPinTuanResultVO goodsPinTuanResult = activityPiecingTogetherMarkMapper.queryPintByMarkId(markId);
            respMap.put("userName",userInfo.getUserName());
            respMap.put("userAvatar",userInfo.getUserAvatar());
            //生成二维码1 是 h5  2 是小程序
            if(null != type && "1".equals(type)){
                byte[] b = QrCodeUtil.createQRCode(150, 150, domainName + "/h5/#/pages/description/descrption?goodsId="+ goodsPinTuanResult.getGoodsId() +"&commonId=" + goodsPinTuanResult.getCommonId() + "&markId=" + markId);
                // 转base 64
                orCode = QrCodeUtil.BASE_PREFIX + Base64Utils.encode(b);
                // 测试 保存本地
//                QrCodeUtil.GenerateImage(Base64Utils.encode(b),null);
            }else{
                //因为生成小程序的二维码参数不能过长，所以将部分请求参数存入redis
                StringBuilder str=new StringBuilder();//定义变长字符串
                Random random=new Random();
                //随机生成数字，并添加到字符串  小程序二维码不能超过 32 位
                for(int i=0;i<8;i++){
                    str.append(random.nextInt(6));
                }
                int num=Integer.parseInt(str.toString());
                //生成markid key
                System.out.println("codeId=" + num+"&codeType=PINTUAN_");
//                orCode = AccessTokenUtil.getminiqrQr("codeId=" + num+"&codeType=PINTUAN", "pages/description/descrption");
//                orCode = domainName + "/mallms/images/" + orCode;
                String sceneStr = "codeId=" + num+"&codeType=PINTUAN";
                String fileName = AccessTokenUtil.getminiqrQr(sceneStr, "pages/description/descrption");
                orCode = QrCodeUtil.BASE_PREFIX + fileName;
                Map<String,Object> map = new HashMap<>();
                map.put("goodsId",goodsPinTuanResult.getGoodsId());
                map.put("commonId",goodsPinTuanResult.getCommonId());
                map.put("markId",markId);
                //将拼团团id存入redis从另外接口查询
                RedisUtil.set("PINTUAN_" + num,JsonUtils.toString(map),60*60*24*7);
            }
            goodsPinTuanResult.setOrCode(orCode);
            respMap.put("goodsPinTuanResult",goodsPinTuanResult);
            return ResponseResult.success(respMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult queryPinTuanBaseDetail(Map<String, Object> param) {

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_GROUPBUY, param.get("token").toString());

        if (userPermissionsResult.getFlag()) {
            ActivityPiecingTogetherEntity entity = this.baseMapper.selectById(param.get("pintuanId").toString());
            if (null != entity) {
                GdsDetailsCommonQueryResultVO commonBase = activityReductionPolicyGoodsMapper.selectByCommonId(entity.getCommonId());
                List<PintuanGoodsSpecListVO> goodsSpecList = this.baseMapper.selectByCommonId5(entity.getCommonId(), param.get("pintuanId").toString());

                entity.setCommonBase(commonBase);
                entity.setGoodsSpecList(goodsSpecList);
            }
            return ResponseResult.success(entity);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult addPinTuanBase(PintuanBaseAddDTO param) {
        // 权限判断
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfo != null) {
            String shopId = userInfo.getShopId();
            param.setShopId(shopId);
            param.setUserId(userInfo.getUserId());
            param.setIsRecommend(0);
            // 拼团持续时间
            param.setStartHour(DateUtils.getDateHost(param.getStartTime(),param.getEndTime()));
            param.setCreatedTime(new Date());
            param.setUpdateTime(new Date());
            Integer commonIsXian = 0;
            // 是否可用，1为可用,0不可用 2 待开启
            Integer status = 0;
            if (DateUtils.belongCalendar(new Date(), param.getStartTime(), param.getEndTime())) {
                status = 1;
                commonIsXian = 4;
            } else {
                status = 2;
                commonIsXian = 4;
            }
            GdsDetailsCommonQueryResultVO goodsMessage = activityReductionPolicyGoodsMapper.selectByCommonId(param.getCommonId());

            if (null == goodsMessage) {
                return ResponseResult.fail(0, "商品不存在或下架，commonid=" + param.getCommonId());
            }

            param.setStatus(status);
            List<PintuanDetailSpecAddDTO> pintuanDetail = param.getGoodsSpecList();
            //活动存在就修改
            if (null == param.getPintuanId()) {
                //将拼团信息 存入活动基础表
                this.baseMapper.insertPintuanBase(param);

                for (PintuanDetailSpecAddDTO pintuanDetailSpecAddParam : pintuanDetail) {
                    pintuanDetailSpecAddParam.setCid(goodsMessage.getCatId());
                    pintuanDetailSpecAddParam.setPintuanId(param.getPintuanId());
                    //存入拼团活动描述表
                    this.baseMapper.insertPintuanDetail(pintuanDetailSpecAddParam);
                }

            } else {
                //拼团信息活动基础表更新
                this.baseMapper.updatePintuanBase(param);
                for (PintuanDetailSpecAddDTO pintuanDetailSpecAddParam : pintuanDetail) {
                    pintuanDetailSpecAddParam.setCid(goodsMessage.getCatId());
                    pintuanDetailSpecAddParam.setPintuanId(param.getPintuanId());
                    //拼团活动描述表更新
                    this.baseMapper.updatePintuanDetail(pintuanDetailSpecAddParam);
                }

            }

            // 查询参与此限时折扣的商品
            List<Integer> commonList = Lists.newArrayList();
            commonList.add(param.getCommonId());
            if (!CollectionUtils.isEmpty(commonList)) {
                CommonIsXianUpdateDTO commonIsXianUpdateParam = new CommonIsXianUpdateDTO();
                // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
                commonIsXianUpdateParam.setCommonIdList(commonList);
                commonIsXianUpdateParam.setCommonIsXian(commonIsXian);
                if (!CollectionUtils.isEmpty(commonList) && commonList.size() > 0) {
                    activityReductionPolicyBaseMapper.updateCommonIsXian3(commonIsXianUpdateParam);
                }

            }

        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(param.getPintuanId());
    }

    @Override
    public ResponseResult deletePinTuanBase(Map<String, Object> param) {
        ActivityPiecingTogetherEntity result = this.baseMapper.selectById(param.get("pintuanId").toString());

        //查询未成团用户 退款
        List<String> expireMarkIdList = activityPiecingTogetherMarkMapper.selectUnformedMarkId(Integer.valueOf(param.get("pintuanId").toString()));
        if(!CollectionUtils.isEmpty(expireMarkIdList)){

            ExpireMarkIdUpdateDTO udpateParam = new ExpireMarkIdUpdateDTO();
            udpateParam.setExpireMarkIdList(expireMarkIdList);
            udpateParam.setStatus(2);//0,等待成团。1为已成团，2为成团失败，3为已完成退款
            activityPiecingTogetherMarkMapper.updateMarkStatus(udpateParam);

            //订单状态更新
            List<String> orderIdList = activityPiecingTogetherTempMapper.selectByMarkId2(expireMarkIdList);
            udpateParam.setOrderIdList(orderIdList);

            try {
                //todo
                //orderServiceClient.checkGroupBookingStatus(udpateParam);
            } catch (Exception e) {
            }
        }

        this.baseMapper.deleteById(param.get("pintuanId").toString());
        activityPiecingTogetherDetailMapper.delete(new LambdaQueryWrapper<ActivityPiecingTogetherDetailEntity>()
                                            .eq(ActivityPiecingTogetherDetailEntity::getPintuanId,param.get("pintuanId").toString()));
        // 查询参与此限时折扣的商品

        if (null != result) {
            List<Integer> commonList = Lists.newArrayList();
            commonList.add(result.getCommonId());
            CommonIsXianUpdateDTO commonIsXianUpdateParam = new CommonIsXianUpdateDTO();
            // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
            commonIsXianUpdateParam.setCommonIdList(commonList);
            commonIsXianUpdateParam.setCommonIsXian(0);
            if (!CollectionUtils.isEmpty(commonList) && commonList.size() > 0) {
                activityReductionPolicyBaseMapper.updateCommonIsXian3(commonIsXianUpdateParam);
            }
        }

        return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
    }

    @Override
    public ResponseResult queryPinTuanBaseList(Map<String, Object> param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(String.valueOf(param.get("token")));

        if (userInfoVO != null) {
            param.put("shopId",userInfoVO.getShopId());

            IPage<ActivityPiecingTogetherEntity> page=this.baseMapper.selectPinTuanBaseList(new Query<ActivityPiecingTogetherEntity>().getPage(param),
                    param);


            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult queryDetail(JoinPintuanParamVO param) {
        JoinPintuanDetailDTO joinPintuanDetail = null;
        // 查询购买者信息
        List<PintuanBuyerMassageDTO> buyerMessage = this.baseMapper.selectBuyerMassage(param.getMarkId());
        // 查询拼团详情
        joinPintuanDetail = this.baseMapper.selectUserIsJoin(param);

        if (null != joinPintuanDetail) {
            // 跳转拼团详情页
            Long overplusTime = DateUtils.getPinTuanOverplusTime(joinPintuanDetail.getCreatedTime(),
                    joinPintuanDetail.getStartHour(), joinPintuanDetail.getEndTime());
            if (overplusTime < 0) {
                return ResponseResult.fail(0, "没有正在拼团的商品，请返回重新拼团");
            }

            String redisKey = YFConfig.YF_USER_TOKEN_USER + param.getToken();
            if (RedisUtil.exists(redisKey)) {
                UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
                String userId = userInfo.getUserId();
                Integer count = activityPiecingTogetherTempMapper.selectCount(new LambdaQueryWrapper<ActivityPiecingTogetherTempEntity>()
                                .eq(ActivityPiecingTogetherTempEntity::getUserId,userId)
                                .eq(ActivityPiecingTogetherTempEntity::getMarkId,param.getMarkId()));
                if (null == count || count.equals(0)) {

                    LOG.info("count值为----------" + count);
                    joinPintuanDetail.setCheckIsSelfMark(0);
                } else {
                    LOG.info("count值为2222----------" + count);
                    joinPintuanDetail.setCheckIsSelfMark(1);
                }
            }
            joinPintuanDetail.setOverplusTime(overplusTime);

            for (PintuanBuyerMassageDTO pintuanBuyerMassage : buyerMessage) {
                String userName = pintuanBuyerMassage.getUserName();
                userName = userName.substring(0, 1) + "****"
                        + userName.substring(userName.length() - 1, userName.length());
                pintuanBuyerMassage.setUserName(userName);
            }
            joinPintuanDetail.setBuyerMessage(buyerMessage);


        } else {
            return ResponseResult.fail(0, "没有正在拼团的商品，请返回重新拼团");
        }

        return ResponseResult.success(joinPintuanDetail);
    }

    @Override
    public ResponseResult queryList(Map<String, Object> param) {
        Integer commonId = Integer.valueOf(param.get("commonId").toString());
        Integer pintuanId = this.baseMapper.selectPintuanByCommonId(commonId);
        param.put("pintuanId",pintuanId);

        IPage<PintuanListResultVO> page=this.baseMapper.selectPintuanList(new Query<PintuanListResultVO>().getPage(param),
                param);

        if (CollectionUtils.isEmpty(page.getRecords())) {
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            for (PintuanListResultVO pintuanListResult : page.getRecords()) {
                long pinTuanOverplusTime = DateUtils.getPinTuanOverplusTime(pintuanListResult.getCreatedTime(),
                        pintuanListResult.getStartHour(), pintuanListResult.getEndTime());
                pintuanListResult.setOverplusTime(pinTuanOverplusTime);
                // 处理用户名
                String userName = pintuanListResult.getUserName();
                userName = userName.substring(0, 1) + "****"
                        + userName.substring(userName.length() - 1, userName.length());
                pintuanListResult.setUserName(userName);

                // 判断是否自己的团

                String redisKey = YFConfig.YF_USER_TOKEN_USER + param.get("token").toString();
                if (RedisUtil.exists(redisKey)) {
                    UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
                    String userId = userInfo.getUserId();
                    Integer count = activityPiecingTogetherTempMapper.selectCount(new LambdaQueryWrapper<ActivityPiecingTogetherTempEntity>()
                            .eq(ActivityPiecingTogetherTempEntity::getUserId,userId)
                            .eq(ActivityPiecingTogetherTempEntity::getMarkId,pintuanListResult.getMarkId()));
                    if (!count.equals(0)) {
                        pintuanListResult.setCheckIsSelfMark(1);
                    } else {
                        pintuanListResult.setCheckIsSelfMark(0);
                    }
                } else {
                    pintuanListResult.setCheckIsSelfMark(0);
                }

            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult getParameterByToken(Map<String, Object> param) {
        try {
            String orCodeType = (String) param.get("orCodeType");
            String orCodeTypeId = (String) param.get("orCodeTypeId");
            String jsonstr = RedisUtil.get(orCodeType + "_" + orCodeTypeId);
            Map maps = (Map) JSON.parse(jsonstr);
            return ResponseResult.success(maps);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }

    }
}

